package com.yimingkeji.redis.service;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Describe:
 * @Auther: zhenlong.yang
 * @Date: 2018/12/3 18:33
 */
@Service
@Slf4j
public class UserService {

    private Map<Integer, User> data = new ConcurrentHashMap<>(10);

    @Cacheable(value = "userCache", key = "#id", unless = "#result==null")
    public User get(int id){
        log.info("不走redis缓存，查询用户，id={}", id);
        return data.get(id);
    }

    @CachePut(value = "userCache", key = "#id")
    public User save(int id, String name){
        data.put(id, new User(id, name));
        return data.get(id);
    }

    @CacheEvict(value = "userCache", key = "#p0")
    public void del(int id){
        data.remove(id);
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class User implements Serializable{
        private int id;
        private String name;
    }
}
